import Vue from 'vue'
import VueResource from 'vue-resource'
import tokens from './plugins/tokens'

Vue.use(VueResource)
const baseUrl = window.API_CONFIG.domain ? window.API_CONFIG.domain : 'http://dev.weijiantou.com:8180/UNIONAPI'
const siteBaseUrl = window.API_CONFIG.drupal || '/api'

Vue.http.options.root = baseUrl

const request = (method) => (path, options) => {
  // Add tokens for api authentication
  options = tokens(options)
  return Vue.http[method](path, {
    timeout: 10 * 1000,
    ...options
  })
  .then(resp => resp.json())
  .catch(err => window.alert(err.message))
}

const toQueryString = (paramsObject) => {
  return Object
    .keys(paramsObject)
    .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(paramsObject[key])}`)
    .join('&')
}

const get = request('get')
// const post = request('post')
// const fakeWXID = 'fake_wxid_for_development_james'

export default {
  // 登录
  login (loginId, password) {
    return get('user/login', {
      params: {
        loginId,
        password
      }
    })
    .then(data => {
      if (data.status === 0) {
        throw new Error(data.message)
      }

      // const uid = this.$cookie.get('uid')
      // if (!uid) {
      window.appRef.$cookie.set('uid', data.data.data.rdid) // api one needed
      // }
      return data.data
    })
  },
  // 绑定账号
  bind (patronId, password, loginId) {
    return get('user/authmap', {
      params: {
        patronId,
        password,
        loginId,
        type: 'WXID'
      }
    }).then(resp => {
      if (resp.status === 0) {
        throw new Error(resp.message)
      }
      return true
    })
  },

  // 解绑
  unbind (patronId, password, loginId) {
    return get('user/unauthmap', {
      params: {
        patronId,
        password,
        loginId,
        type: 'WXID'
      }
    }).then(resp => {
      if (resp.status === 0) {
        throw new Error(resp.message)
      }
      return true
    })
  },

  // 绑定卡
  bindCard (cardNo, password) {
  },
  // 解绑卡

  /**
   * 个人资料
   * @param  {[type]} loginId
   * @param  {String} type    [WXID || ID_CARD || RDID]
   */
  userInfo (loginId, type = 'RDID') {
    return get('user/loadby', {
      params: {
        loginId,
        type
      }
    }).then(({data}) => {
      if (data.data === null) {
        window.appRef.$cookie.delete('uid')
        throw new Error('用户信息获取失败')
      }
      window.appRef.$cookie.set('uid', data.data.rdid)
      return {
        name: data.data.name,
        rdid: data.data.rdid,
        status: data.data.status,
        address: data.data.address,
        phone: data.data.phone,
        email: data.data.email,
        cardId: data.data.cardid
      }
    })
  },
  // 更新个人资料
  userUpdate (params) {
    return get('user/update', { params }).then(resp => {
      if (resp.status === 0) {
        // Promise.reject(resp.message)
        throw new Error(resp.message)
      }
      return true
    })
  },

  // 更改密码
  updatePassword (params) {
    // password,
    // newPassword,
    // sessionId / patronId
    return get('user/upwd', { params }).then(resp => {
      if (resp.status === 0) {
        // Promise.reject(resp.message)
        throw new Error(resp.message)
      }
      return true
    })
  },

  // 挂失
  reportLost (params) {
    // password
    return get('user/lost', { params }).then(resp => {
      if (resp.status === 0) {
        throw new Error(resp.message)
      }
      return true
    })
  },

  // 预约
  reserve (params) {
    return get('circulate/reserve', { params }).then(resp => {
      if (resp.status === 0) {
        throw new Error(resp.message)
      }
      return true
    })
  },

  // 预约
  unReserve (params) {
    return get('circulate/unreserve', { params }).then(resp => {
      if (resp.status === 0) {
        throw new Error(resp.message)
      }
      return true
    })
  },

  // 我的预约
  reservations (params) {
    return get('circulate/reservations', { params })
  },

  // 图书搜索
  search (keyname = 'title', keyword, page) {
    const params = { page }
    params[keyname] = keyword

    return get('search/simple', { params }).then(resp => {
      if (resp.status === 0) {
        throw new Error(resp.message)
      }
      return resp.data.data
    })
  },
  // 图书馆分馆列表
  subLibs () {
    return get('zones')
  },
  // 图书信息
  bookInfo (bookRecNo) {
    return get('search/detail', {
      params: {
        bookrecno: bookRecNo
      }
    }).then(resp => {
      if (resp.status === 0) {
        throw new Error(resp.message)
      }
      return resp.data
    })
  },
  // 续借
  renew (itemId, patronId) {
    return get('circulate/renew', {
      params: {
        itemId,
        patronId
      }
    }).then(response => {
      if (response.status === 0) {
        let msg = response.message || '续借失败'
        msg = msg.replace(`[${response.detail}]`, '')
        throw new Error(msg)
      }
      return true
    })
  },
  // 当前借阅
  borrowCurrent (patronId) {
    return get('user/loans', {
      params: {
        patronId
      }
    }).then(resp => {
      console.log('loans', resp.data)
      return resp.data
    })
  },
  // 借阅历史
  borrowHistory (patronId) {
    return get('user/history', {
      params: {
        patronId
      }
    }).then(resp => {
      console.log('history', resp.data)
      return resp.data
    })
  },
  jiangou (params) {
    return get(`${siteBaseUrl}/api/book/recommend`, { params }).then((resp) => {
      console.log(resp)
      if (resp.data.errMsg) throw new Error(resp.data.errMsg)
      return true
    })
  },
  fetchNews (limit, page) {
    const params = {
      type: 'news',
      limit,
      page
    }
    return get(`${siteBaseUrl}/node`, { params }).then((resp) => {
      return {
        list: resp.list,
        isFirst: !resp.prev,
        isLast: !resp.next
      }
    })
  },
  fetchNode (id) {
    return get(`${siteBaseUrl}/node/${id}`)
  },
  // 二维码
  qrcode (patronId) {
    let opt = {params: {patronId: patronId}}
    opt = tokens(opt)
    return `${baseUrl}/user/qrcode?` + toQueryString(opt.params)
  },

  getStats () {
    return get('stat/summary')
  },
  getDouban (isbn) {
    return new Promise((resolve, reject) => {
      Vue.http.jsonp('https://api.douban.com/v2/book/isbn/' + isbn)
        .then((resp) => {
          window.res = resp
          console.log(resp)
          resolve(resp.body.alt)
        })
        .catch(reject)
    })
  }
}
